package com.leyou.item.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.utils.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pojo.Brand;
import tk.mybatis.mapper.entity.Example;

import java.util.List;


/**
 * Author: Saka
 * Date: 2019/1/15
 * Time: 21:01
 */
@Service
public class BrandServiceImpl implements BrandService {
    @Autowired
    private BrandMapper brandMapper;

    @Override
    public PageResult<Brand> queryBrandByPageAndSort(Integer page, Integer rows,
                                                     String sortBy, Boolean desc,
                                                     String key) {
        //开始分页
        PageHelper.startPage(page, rows);
        //过滤
        Example example = new Example(Brand.class);
        if (StringUtils.isNoneBlank(key)) {
            example.createCriteria().andLike("name", "%" + key + "%").
                    orEqualTo("letter",key.toUpperCase());


        }
        if (StringUtils.isNoneBlank(sortBy)) {
            //排序
            String orderByClause = sortBy + (desc ? "DESC" : "ASC");
            example.setCountProperty(orderByClause);

        }
        //查询
        Page<Brand> brands = (Page<Brand>) brandMapper.selectByExample(example);

        return new PageResult<>(brands.getTotal(), brands);
    }

    //事务
    @Transactional
    @Override
    public void saveBrand(Brand brand, List<Long> cids) {
        //新增品牌信息
        this.brandMapper.insertSelective(brand);
        //新增品牌和分类中间表
        cids.forEach(cid->{
            this.brandMapper.insertCategoryBrand(cid, brand.getId());
        });
    }
    @Transactional
    @Override
    public void updataBrand(Brand brand, List<Long> cids) {
        //先删除和分类的所有关系,然后重新建立关系

        this.brandMapper.deleteBrandCategory(brand.getId());

        //brand可以直接修改了
        this.brandMapper.updateByPrimaryKeySelective(brand);

        cids.forEach(cid->{
            this.brandMapper.insertCategoryBrand(cid, brand.getId());
        });
    }

    @Override
    public Brand queryBrandById(Long brandId) {
        return this.brandMapper.selectByPrimaryKey(brandId);
    }

    @Override
    public void deleteByCategoryBrandId(Long bid) {
        this.brandMapper.deleteByCategoryBrandId(bid);
    }

    @Override
    public void deleteByBrandId(Long bid) {
        this.brandMapper.deleteByBrandId(bid);
    }

    @Override
    public List<Brand> queryBrandByCategory(Long cid) {

        return this.brandMapper.queryBrandByCategory(cid);
    }
}
